<?php
require_once 'TVB/pms/pdes/common//util/ChangeLogTools.class.php';

class MisHelper
{
   
    private $error_msg;
    private $episode_jobs = array();
    private $programme_jobs = array();
	private $link_list = array();
	private $change_logs = array();

    public function import()
    {
        $mis_api = new MisApi();
        $jobs = $mis_api->getDataByApi('getSendReadyJob',array());
		$this->_uniqueJob($jobs);
		$programmes = array();
        $episodes = array();
        if(!empty($jobs)) {
            foreach($jobs as $job) {
                $job = (array)$job;
                if( (int)$job['EPI_PID'] > 0 ) {
                    $episodes[] = $job;
                } else {
                    $programmes[] = $job; 
                }
            }
        }

        try {
			$ret = $this->importProgramme($programmes);
            Model::$dbo['w']->beginTransaction();
            $ret = $this->importEpisode($episodes);
            Model::$dbo['w']->commit();

			# change_log
			array_walk($this->change_logs, 'change_log::updateOne');

            if(!empty($this->error_msg)) {
                //send mail 
                //mail(CommonUtils::getAdminMail(),"MIS Error Message, At ".trim(`hostname`) , print_r($this->error_msg,1));
                print_r($this->error_msg);
                mail(CommonUtils::getAdminMail(),"MIS Import Error Message, At ".trim(`hostname`) , print_r($this->error_msg,1));
            }
            $all_receive_jobs = array_merge($this->episode_jobs,$this->programme_jobs);
            $is_error = false;
            $msg = '';
            foreach($all_receive_jobs as $key => $job) {
                $mis_api  = new MisApi();
                $array = array(
                    'CO_CODE'   => $job['CO_CODE'],
                    'PGM_ID'    => sprintf('%09d', $job['PGM_ID']),
                    'EPI_PID'   => $job['EPI_PID'],
                );
                $status = $mis_api->getDataByApi('sendJobReceive',$array);
                if($status && property_exists($status,'ERROR')) {
                    $is_error = true;
                    $msg .= (string)$status->ERROR."\ndetail :\n".'PGM_ID = '.$job['PGM_ID'].',epi_pid = '.$job['EPI_PID'].";\n";
                }
            }

            if($is_error) {
                print_r($msg);
                mail(CommonUtils::getAdminMail(),"MIS send job receive Error Message, At ".trim(`hostname`) , print_r($msg,1));
            }
        } catch(PDOException $e) {
            print_r($e->getMessage());
            mail(CommonUtils::getAdminMail(),"MIS DB Error Message, At ".trim(`hostname`) , print_r($e->getMessage(),1));
            Model::$dbo['w']->rollBack();
            return false;
        }

    }

	public function sendNewMailToPD()
	{
		$link_list = $this->getLinkList();
		if (empty($link_list)) return FALSE;

		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";	

		$message = 'There have some data come from MIS : <br /><br /> ';
		$message .= implode("\r\n<br /><br />\r\n", $link_list);

		mail(CommonUtils::getAdminMail('PDTeam'), 'MIS information', $message, $headers);
	}

	public function SendMailToPD(){
		$mailHeader = "There have some datas to come from MIS :\n";
		$pdesList = array();
		$mis_data = Model::selectBySql("SELECT pdes_id,type FROM mis_log where modified_at > now() - interVAL 5 MINUTE order by modified_at DESC ;");
		if(!$mis_data){
			error_log('no record');
			return false;
		}
		foreach($mis_data as $job){
			$job = (array)$job;
			$ret[] =$job;
		}
		//get Jobs CO_CODE and PGM_ID
		for($i = 0; $i < count($ret); $i++){
			$id[] = $ret[$i]['pdes_id'];
			$type[] = $ret[$i]['type'];
			$relation[] = mis_pdes::getRelation(array('pdes_id' => $id[$i],
								  'type' => $type[$i]
								  )
							);
			$pdesList[] = $relation[$i][0]['pdes_pid'];
		};
		//get Path and id
        $sql = 'select p.id,p.path,l.title from programme p left join `programme-language` l ON p.id = l.programme_id where p.id in('.implode(",",$pdesList).') AND l.language_id = 1;';
		$pdesIdandPath = Model::selectBySql($sql);
		var_dump($pdesIdandPath);
		//Mark down the information
		echo $mailHeader;
		$mail = $mailHeader;
			for($i = 0; $i < count($ret); $i++){
				for($y = 0; $y < count($relation[$i]); $y++){
					$type = 'Type : '.$relation[$i][$y]['type']."\n";
					$pdes_pid = 'pdes id : '.$relation[$i][$y]['pdes_pid']."\n";
					$pdes_eid = 'episode id : '.$relation[$i][$y]['pdes_eid']."\n";
					$pdes_id = $relation[$i][$y]['pdes_id']."\n";
					$time  = 'time : '.date('Y-m-d h:i:s');
					//get key values
					foreach($pdesIdandPath as $key => $values){
						if($values['id'] == $relation[$i][$y]['pdes_pid']){
							$path = 'programme path : '.$pdesIdandPath[$key]['path']."\n";
							$programmeName = 'programme name : '.$pdesIdandPath[$key]['title']."\n";
						}
					}				
					switch($relation[$i][$y]['type']){
						case 'programme':
							$mailinfo = $type.$pdes_pid.$path.$programmeName.$time;
							echo $mailinfo."\n";
							$mail .= $mailinfo."\n";
							break;
						case 'episode':
							$mailinfo = $type.$pdes_pid.$pdes_eid.$path.$programmeName;
							echo $mailinfo."\n";
							$mail .= $mailinfo."\n";
							break;
						case 'cast':
							$mailinfo = $type.$pdes_pid.$pdes_eid.'cast id : '.$pdes_id.$path.$programmeName;
							echo $mailinfo."\n";		
							$mail .= $mailinfo."\n";
							break;
						case 'info_address':
								$mailinfo = $type.$pdes_pid.$pdes_eid.'address id : '.$pdes_id.$path.$programmeName;
								echo $mailinfo."\n";
								$mail .= $mailinfo."\n";
								break;
						case 'info_biography':
								$mailinfo = $type.$pdes_pid.$pdes_eid.'biography id : '.$pdes_id.$path.$programmeName;
								echo $mailinfo."\n";
								$mail .= $mailinfo."\n";
								break;
						case 'info_recipe':
								$mailinfo = $type.$pdes_pid.$pdes_eid.'recipe id : '.$pdes_id.$path.$programmeName;
								echo $mailinfo."\n";
								$mail .= $mailinfo."\n";
								break;
						case 'info_song':
								$mailinfo = $type.$pdes_pid.$pdes_eid.'song id : '.$pdes_id.$path.$programmeName;
								echo $mailinfo."\n";
								$mail .= $mailinfo."\n";
								break;
						case 'info_q_a':
								$mailinfo = $type.$pdes_pid.$pdes_eid.'q_a id : '.$pdes_id.$path.$programmeName;
								echo $mailinfo."\n";
								$mail .= $mailinfo."\n";
								break;
						case 'info_general_information':
								$mailinfo = $type.$pdes_pid.$pdes_eid.'general info id : '.$pdes_id.$path.$programmeName;
								echo $mailinfo."\n";
								$mail .= $mailinfo."\n";
								break;
					}	
				}	
			}
		mail(CommonUtils::getAdminMail('PDTeam'),'MIS information',$mail);
	}
    private function importProgramme($programmes)
    {
        if(!empty($programmes)) {
            $programmeHelper = new MisProgramme();
            $ret = $programmeHelper->import($programmes);
            $this->error_msg .= $programmeHelper->getErrorMessage()."\n";
            $this->programme_jobs = $programmeHelper->getReceiveJobs();
			$this->link_list = array_merge($this->link_list, $programmeHelper->getLinkList());

			# change_log
			$this->change_logs = array_merge($this->change_logs,$programmeHelper->getChangeLogs());
        } else {
            //$this->error_msg .= "no any programme exists."."\n";
            $ret = false;
        }

        return $ret;
    }
    
    private function importEpisode($episodes)
    {
        $episode = new MisEpisodeHelper(); 
        if(!empty($episodes)) {
            foreach($episodes as $job) {
                $programme_id = programme_cpl::findPdesProgramme($job['PGM_ID'], $job['CO_CODE']);
                if(!empty($programme_id)) {
                    $rs = $episode->import($job);
					$this->link_list = array_merge($this->link_list, $episode->getLinkList());
                    $this->error_msg .= $episode->getErrorMessage()."\n";

					# change_log
					$this->change_logs = array_merge($this->change_logs,$episode->getChangeLogs());
                } else {
                    $this->error_msg .= "Import episode fail! Because programme(mis_pid:".$job['PGM_ID'].") is not exists in pdes."."\n";
                    $rs = false;
                }
            }
        } else {
            $rs = false;
        }

        $this->episode_jobs = $episode->getReceiveJobs();

        return $rs;
    }

    // bug 4139
    private function _uniqueJob($jobs)
    {
        $unique = array();
        for ($i=0; $i<count($jobs->Job); ) {
            $job = $jobs->Job[$i];
            $mis_key = (string) $job->CO_CODE . (string) $job->PGM_ID . (string) $job->EPI_ID;
            if (in_array($mis_key, $unique)) {
                unset($jobs->Job[$i]);
            } else {
                $unique[] = $mis_key;
                $i++;
            }
        }
    }

	public function getLinkList()
	{
		return $this->link_list;
	}
}
?>
